package 力扣._394_字符串解码;

import java.util.Stack;

public class Solution2 {
    //这个方法并不可以，因为【】可能嵌套，还是得用栈来解决
    //直接正则表达式
    public String decodeString(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != ']')
                stack.push(c);
            else {
                //取出括号中字符
                StringBuilder s1 = new StringBuilder();
                char t = 0;
                while (true) {
                    t = stack.pop();
                    if(t=='[')
                        break;
                    s1.insert(0, t);
                }
                //取出括号前数字
                StringBuilder s_num = new StringBuilder();
                while (!stack.isEmpty()&&stack.peek()>='0'&&stack.peek()<='9'){
                    t = stack.pop();
                    s_num.insert(0,t);
                }
                int num = Integer.parseInt(s_num.toString());
                String s2 = s1.toString().repeat(num);
                //再入栈
                for (int j = 0; j < s2.length(); j++)
                    stack.push(s2.charAt(j));
            }
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty())
            result.insert(0,stack.pop());
        return result.toString();


    }

    public static void main(String[] args) {
        String s = new Solution2().decodeString("abc3[cd]xyz");
        System.out.println(s);
    }
}
